package com.buba.springcloud.filter;
import cn.hutool.json.JSONObject;
import com.buba.springcloud.entities.CommonResult;
import com.buba.springcloud.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;

@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("########### come in MyLogGateWayFilter {}###########", new Date());
        String uri = exchange.getRequest().getURI().getPath();
        System.out.println(uri);
        if (uri.indexOf("backstagesupporter") == -1) {
            if (uri.indexOf("login")==-1) {
                String token = exchange.getRequest().getHeaders().getFirst("token");
                try {
                    Claims claims = JwtUtil.parseJWT(token);
                } catch (Exception e) {
                    ServerHttpResponse serverHttpResponse = exchange.getResponse();
                    serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
                    CommonResult result = new CommonResult(300, "用户信息过期，请重新登录");
                    JSONObject res = new JSONObject(result);
                    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(res.toString().getBytes());
                    exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    exchange.getResponse().getHeaders().setAcceptCharset(Arrays.asList(StandardCharsets.UTF_8));
                    return exchange.getResponse().writeWith(Flux.just(buffer));
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
